import { Tabs, Table, Button, Space, Input, Modal, Form, Select, message, Card, Statistic, Row, Col, Tag, Typography } from '@/utils/antd-imports';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FileTextOutlined, UserOutlined, ProjectOutlined, TeamOutlined, ClockCircleOutlined, DollarOutlined } from '@/utils/icons';
import React, { useState } from 'react';





import DatePicker from 'antd/es/date-picker';












const { TabPane } = Tabs;
const { Search } = Input;
const { Option } = Select;
const { Title, Text } = Typography;

// 人事合同数据
const personnelContracts = [
  {
    key: '1',
    contractId: 'HT20250001',
    employeeName: '张三',
    employeeId: 'EMP001',
    contractType: '劳动合同',
    startDate: '2025-01-01',
    endDate: '2027-12-31',
    status: '生效中',
    department: '技术部'
  },
  {
    key: '2',
    contractId: 'HT20250002',
    employeeName: '李四',
    employeeId: 'EMP002',
    contractType: '劳务合同',
    startDate: '2025-03-15',
    endDate: '2026-03-14',
    status: '生效中',
    department: '市场部'
  },
  {
    key: '3',
    contractId: 'HT20250003',
    employeeName: '王五',
    employeeId: 'EMP003',
    contractType: '实习协议',
    startDate: '2025-06-01',
    endDate: '2025-12-31',
    status: '已到期',
    department: '人力资源部'
  },
  {
    key: '4',
    contractId: 'HT20250004',
    employeeName: '赵六',
    employeeId: 'EMP004',
    contractType: '劳动合同',
    startDate: '2025-02-01',
    endDate: '2028-01-31',
    status: '生效中',
    department: '产品部'
  }
];

// 项目合同数据
const projectContracts = [
  {
    key: '1',
    contractId: 'XMHT20250001',
    projectName: '智慧城市建设项目',
    projectCode: 'PROJ001',
    clientName: '市政府',
    contractAmount: '5,000,000',
    signDate: '2025-02-10',
    startDate: '2025-03-01',
    endDate: '2026-12-31',
    status: '执行中'
  },
  {
    key: '2',
    contractId: 'XMHT20250002',
    projectName: '企业ERP系统开发',
    projectCode: 'PROJ002',
    clientName: 'ABC科技有限公司',
    contractAmount: '1,200,000',
    signDate: '2025-04-05',
    startDate: '2025-04-15',
    endDate: '2025-10-14',
    status: '已完成'
  },
  {
    key: '3',
    contractId: 'XMHT20250003',
    projectName: '电商平台升级',
    projectCode: 'PROJ003',
    clientName: 'XYZ电商公司',
    contractAmount: '2,500,000',
    signDate: '2025-05-20',
    startDate: '2025-06-01',
    endDate: '2026-05-31',
    status: '执行中'
  }
];

// 项目人员合同数据
const projectPersonnelContracts = [
  {
    key: '1',
    contractId: 'XMHT20250001-001',
    projectName: '智慧城市建设项目',
    projectCode: 'PROJ001',
    employeeName: '张三',
    employeeId: 'EMP001',
    role: '项目经理',
    startDate: '2025-03-01',
    endDate: '2026-12-31',
    salary: '25,000',
    status: '生效中'
  },
  {
    key: '2',
    contractId: 'XMHT20250001-002',
    projectName: '智慧城市建设项目',
    projectCode: 'PROJ001',
    employeeName: '李四',
    employeeId: 'EMP002',
    role: '前端开发',
    startDate: '2025-03-01',
    endDate: '2026-12-31',
    salary: '18,000',
    status: '生效中'
  },
  {
    key: '3',
    contractId: 'XMHT20250002-001',
    projectName: '企业ERP系统开发',
    projectCode: 'PROJ002',
    employeeName: '王五',
    employeeId: 'EMP003',
    role: '测试工程师',
    startDate: '2025-04-15',
    endDate: '2025-10-14',
    salary: '15,000',
    status: '已结束'
  },
  {
    key: '4',
    contractId: 'XMHT20250003-001',
    projectName: '电商平台升级',
    projectCode: 'PROJ003',
    employeeName: '赵六',
    employeeId: 'EMP004',
    role: '后端开发',
    startDate: '2025-06-01',
    endDate: '2026-05-31',
    salary: '20,000',
    status: '生效中'
  }
];

const ContractManagement = () => {
  const [activeTab, setActiveTab] = useState('1');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('add');
  const [currentContract, setCurrentContract] = useState(null);
  const [form] = Form.useForm();

  // 计算统计指标
  const calculateStats = () => {
    // 人事合同统计
    const personnelStats = {
      total: personnelContracts.length,
      active: personnelContracts.filter(c => c.status === '生效中').length,
      expired: personnelContracts.filter(c => c.status === '已到期').length,
      departments: [...new Set(personnelContracts.map(c => c.department))].length
    };

    // 项目合同统计
    const projectStats = {
      total: projectContracts.length,
      active: projectContracts.filter(c => c.status === '执行中').length,
      completed: projectContracts.filter(c => c.status === '已完成').length,
      totalAmount: projectContracts.reduce((sum, c) => sum + parseInt(c.contractAmount.replace(/,/g, '')), 0)
    };

    // 项目人员合同统计
    const projectPersonnelStats = {
      total: projectPersonnelContracts.length,
      active: projectPersonnelContracts.filter(c => c.status === '生效中').length,
      ended: projectPersonnelContracts.filter(c => c.status === '已结束').length,
      avgSalary: Math.round(projectPersonnelContracts.reduce((sum, c) => sum + parseInt(c.salary.replace(/,/g, '')), 0) / projectPersonnelContracts.length)
    };

    return { personnelStats, projectStats, projectPersonnelStats };
  };

  const { personnelStats, projectStats, projectPersonnelStats } = calculateStats();

  // 处理标签页切换
  const handleTabChange = (key) => {
    setActiveTab(key);
  };

  // 显示添加合同模态框
  const showAddModal = () => {
    setModalType('add');
    form.resetFields();
    setIsModalVisible(true);
  };

  // 显示编辑合同模态框
  const showEditModal = (record) => {
    setModalType('edit');
    setCurrentContract(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  // 处理模态框确认
  const handleModalOk = () => {
    form.validateFields().then(values => {
      message.success(modalType === 'add' ? '合同添加成功' : '合同更新成功');
      setIsModalVisible(false);
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  };

  // 处理模态框取消
  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  // 处理删除合同
  const handleDelete = (contractId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条合同记录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        message.success('合同删除成功');
      }
    });
  };

  // 人事合同列定义
  const personnelColumns = [
    {
      title: '合同编号',
      dataIndex: 'contractId',
      key: 'contractId',
      width: 150,
      fixed: 'left'
    },
    {
      title: '员工姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
      width: 120,
      render: (text) => (
        <span>
          <UserOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '员工工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
      width: 120
    },
    {
      title: '合同类型',
      dataIndex: 'contractType',
      key: 'contractType',
      width: 120
    },
    {
      title: '开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '结束日期',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text) => {
        let color = '';
        if (text === '生效中') color = 'green';
        if (text === '已到期') color = 'orange';
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.contractId)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  // 项目合同列定义
  const projectColumns = [
    {
      title: '合同编号',
      dataIndex: 'contractId',
      key: 'contractId',
      width: 150,
      fixed: 'left'
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 180,
      render: (text) => (
        <span>
          <ProjectOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 120
    },
    {
      title: '客户名称',
      dataIndex: 'clientName',
      key: 'clientName',
      width: 150
    },
    {
      title: '合同金额',
      dataIndex: 'contractAmount',
      key: 'contractAmount',
      width: 120,
      render: (text) => `¥${text}`
    },
    {
      title: '签订日期',
      dataIndex: 'signDate',
      key: 'signDate',
      width: 120
    },
    {
      title: '开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '结束日期',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text) => {
        let color = '';
        if (text === '执行中') color = 'green';
        if (text === '已完成') color = 'blue';
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.contractId)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  // 项目人员合同列定义
  const projectPersonnelColumns = [
    {
      title: '合同编号',
      dataIndex: 'contractId',
      key: 'contractId',
      width: 150,
      fixed: 'left'
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 180,
      render: (text) => (
        <span>
          <ProjectOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 120
    },
    {
      title: '员工姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
      width: 120,
      render: (text) => (
        <span>
          <UserOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '员工工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
      width: 120
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120
    },
    {
      title: '开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '结束日期',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120
    },
    {
      title: '薪资',
      dataIndex: 'salary',
      key: 'salary',
      width: 120,
      render: (text) => `¥${text}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text) => {
        let color = '';
        if (text === '生效中') color = 'green';
        if (text === '已结束') color = 'gray';
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.contractId)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <Tabs
        type="card"
        activeKey={activeTab}
        onChange={handleTabChange}
        tabBarExtraContent={
          <Space>
            <Search 
              placeholder="搜索合同..." 
              allowClear 
              style={{ width: 200 }} 
              prefix={<SearchOutlined />}
            />
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={showAddModal}
            >
              新增合同
            </Button>
          </Space>
        }
      >
        <TabPane tab="人事合同" key="1">
          {/* 人事合同统计指标 */}
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="合同总数"
                  value={personnelStats.total}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="生效中合同"
                  value={personnelStats.active}
                  prefix={<FileTextOutlined style={{ color: '#52c41a' }} />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="已到期合同"
                  value={personnelStats.expired}
                  prefix={<FileTextOutlined style={{ color: '#faad14' }} />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="涉及部门"
                  value={personnelStats.departments}
                  prefix={<TeamOutlined style={{ color: '#722ed1' }} />}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
          </Row>

          <Table
            columns={personnelColumns}
            dataSource={personnelContracts}
            bordered
            size="middle"
            scroll={{ x: 1300 }}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条合同记录`
            }}
          />
        </TabPane>
        <TabPane tab="项目合同" key="2">
          {/* 项目合同统计指标 */}
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="合同总数"
                  value={projectStats.total}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="执行中项目"
                  value={projectStats.active}
                  prefix={<ProjectOutlined style={{ color: '#52c41a' }} />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="已完成项目"
                  value={projectStats.completed}
                  prefix={<ProjectOutlined style={{ color: '#13c2c2' }} />}
                  valueStyle={{ color: '#13c2c2' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="合同总金额"
                  value={projectStats.totalAmount}
                  prefix="¥"
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
          </Row>

          <Table
            columns={projectColumns}
            dataSource={projectContracts}
            bordered
            size="middle"
            scroll={{ x: 1500 }}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条合同记录`
            }}
          />
        </TabPane>
        <TabPane tab="项目人员合同" key="3">
          {/* 项目人员合同统计指标 */}
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="合同总数"
                  value={projectPersonnelStats.total}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="生效中合同"
                  value={projectPersonnelStats.active}
                  prefix={<UserOutlined style={{ color: '#52c41a' }} />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="已结束合同"
                  value={projectPersonnelStats.ended}
                  prefix={<UserOutlined style={{ color: '#faad14' }} />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="平均薪资"
                  value={projectPersonnelStats.avgSalary}
                  prefix="¥"
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
          </Row>

          <Table
            columns={projectPersonnelColumns}
            dataSource={projectPersonnelContracts}
            bordered
            size="middle"
            scroll={{ x: 1500 }}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条合同记录`
            }}
          />
        </TabPane>
      </Tabs>

      {/* 添加/编辑合同模态框 */}
      <Modal
        title={modalType === 'add' ? '新增合同' : '编辑合同'}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={700}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={currentContract || {}}
        >
          {activeTab === '1' && (
            <>
              <Form.Item
                label="合同编号"
                name="contractId"
                rules={[{ required: true, message: '请输入合同编号' }]}
              >
                <Input placeholder="请输入合同编号" />
              </Form.Item>
              <Form.Item
                label="员工姓名"
                name="employeeName"
                rules={[{ required: true, message: '请输入员工姓名' }]}
              >
                <Input placeholder="请输入员工姓名" />
              </Form.Item>
              <Form.Item
                label="合同类型"
                name="contractType"
                rules={[{ required: true, message: '请选择合同类型' }]}
              >
                <Select placeholder="请选择合同类型">
                  <Option value="劳动合同">劳动合同</Option>
                  <Option value="劳务合同">劳务合同</Option>
                  <Option value="实习协议">实习协议</Option>
                  <Option value="兼职协议">兼职协议</Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="开始日期"
                name="startDate"
                rules={[{ required: true, message: '请选择开始日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                label="结束日期"
                name="endDate"
                rules={[{ required: true, message: '请选择结束日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </>
          )}
          
          {activeTab === '2' && (
            <>
              <Form.Item
                label="合同编号"
                name="contractId"
                rules={[{ required: true, message: '请输入合同编号' }]}
              >
                <Input placeholder="请输入合同编号" />
              </Form.Item>
              <Form.Item
                label="项目名称"
                name="projectName"
                rules={[{ required: true, message: '请输入项目名称' }]}
              >
                <Input placeholder="请输入项目名称" />
              </Form.Item>
              <Form.Item
                label="客户名称"
                name="clientName"
                rules={[{ required: true, message: '请输入客户名称' }]}
              >
                <Input placeholder="请输入客户名称" />
              </Form.Item>
              <Form.Item
                label="合同金额"
                name="contractAmount"
                rules={[{ required: true, message: '请输入合同金额' }]}
              >
                <Input placeholder="请输入合同金额" />
              </Form.Item>
              <Form.Item
                label="签订日期"
                name="signDate"
                rules={[{ required: true, message: '请选择签订日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </>
          )}
          
          {activeTab === '3' && (
            <>
              <Form.Item
                label="合同编号"
                name="contractId"
                rules={[{ required: true, message: '请输入合同编号' }]}
              >
                <Input placeholder="请输入合同编号" />
              </Form.Item>
              <Form.Item
                label="项目名称"
                name="projectName"
                rules={[{ required: true, message: '请输入项目名称' }]}
              >
                <Input placeholder="请输入项目名称" />
              </Form.Item>
              <Form.Item
                label="员工姓名"
                name="employeeName"
                rules={[{ required: true, message: '请输入员工姓名' }]}
              >
                <Input placeholder="请输入员工姓名" />
              </Form.Item>
              <Form.Item
                label="角色"
                name="role"
                rules={[{ required: true, message: '请输入角色' }]}
              >
                <Input placeholder="请输入角色" />
              </Form.Item>
              <Form.Item
                label="薪资"
                name="salary"
                rules={[{ required: true, message: '请输入薪资' }]}
              >
                <Input placeholder="请输入薪资" />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default ContractManagement;